#region Microsoft Public License
/*
 * (c) Copyright Chenjun Wu. http://utablesdk.codeplex.com
 * 
 * This source is subject to the Microsoft Public License (Ms-PL).
 * Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
 * All other rights reserved.
 */
#endregion

﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using UTable.Input;
using UTable.Input.MultiTouch;
using UTable.Objects;
using UTable.Objects.Controls;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Controls.Primitives;

namespace UTable.Objects.Controls
{
    /// <summary>
    /// Interaction logic for UFileExplorer.xaml
    /// </summary>
    public partial class UFileExplorer : UUserControl
    {
        public UFileExplorer()
        {
            InitializeComponent();
            this.DirectoryPath = "Computer";
        }

        public void Back()
        {
            if (CheckCanBack())
            {
                DirectoryInfo info = System.IO.Directory.GetParent(this.DirectoryPath);
                if (info != null)
                    this.DirectoryPath = info.FullName;
                else
                    this.DirectoryPath = "Computer";
            }
        }

        public bool CanBack
        {
            get { return (bool)GetValue(CanBackProperty); }
            set { SetValue(CanBackProperty, value); }
        }

        public static readonly DependencyProperty CanBackProperty =
            DependencyProperty.Register("CanBack", typeof(bool), typeof(UFileExplorer), new UIPropertyMetadata(false));

        public bool ShowHiddenFiles
        {
            get { return (bool)GetValue(ShowHiddenFilesProperty); }
            set { SetValue(ShowHiddenFilesProperty, value); }
        }

        public static readonly DependencyProperty ShowHiddenFilesProperty =
            DependencyProperty.Register("ShowHiddenFiles", typeof(bool), typeof(UFileExplorer), new UIPropertyMetadata(false));


        public FileSelectionMode SelectionMode
        {
            get { return (FileSelectionMode)GetValue(SelectionModeProperty); }
            set { SetValue(SelectionModeProperty, value); }
        }

        public static readonly DependencyProperty SelectionModeProperty =
            DependencyProperty.Register("SelectionMode", typeof(FileSelectionMode), typeof(UFileExplorer), new UIPropertyMetadata(FileSelectionMode.Single));


        public List<FileItemData> SelectedFiles = new List<FileItemData>();

        private bool CheckCanBack()
        {
            if (this.DirectoryPath == "Computer")
                return false;
            return true;
        }

        public void Fresh()
        {
            if (DirectoryPath == "Computer")
            {
                string[] DriveList = Environment.GetLogicalDrives();
                Files = new ObservableCollection<FileItemData>();
                foreach (String d in DriveList)
                {
                    if (Directory.Exists(d))
                        Files.Add(new FileItemData(d));
                }
            }
            else
            {
                List<String> files = new List<string>(System.IO.Directory.GetFiles(DirectoryPath));
                files.AddRange(System.IO.Directory.GetDirectories(DirectoryPath));
                files.Sort();
                Files.Clear();
                foreach (String file in files)
                {
                    if (ShowHiddenFiles || (File.GetAttributes(file) & FileAttributes.Hidden) != FileAttributes.Hidden)
                        Files.Add(new FileItemData(file));
                }
            }

            try
            {

            }
            catch (System.Exception e)
            {
                // throw e;
                Console.WriteLine(e.Message);
                //UWarnDialog dialog = new UWarnDialog();
                //dialog.Message = e.Message;
                //dialog.Open();
            }
        }

        public bool CanGotoFolder(String folderPath)
        {
            if (folderPath == "Computer")
                return true;
            try
            {
                System.IO.Directory.GetFiles(folderPath);
            }
            catch (System.Exception e)
            {
                return false;
            }
            return true;
        }

        public String DirectoryPath
        {
            get { return (String)GetValue(DirectoryPathProperty); }
            set 
            {
                if (!CanGotoFolder(value))
                {
                    UWarnDialog dialog = new UWarnDialog();
                    dialog.Message = "Cannot goto this folder!";
                    dialog.Open();
                    return;
                }

                SetValue(DirectoryPathProperty, value);
                Fresh();
                CanBack = CheckCanBack();
            }
        }

        public bool SelectFile(FileItemData file)
        {
            if (!this.Files.Contains(file))
                return false;

            switch (SelectionMode)
            {
                case FileSelectionMode.None:
                    // do nothing
                    return false;
                case FileSelectionMode.Single:
                    if (!SelectedFiles.Contains(file))
                    {
                        if (SelectedFiles.Count > 0)
                            SelectedFiles[0].IsSelected = false;
                        SelectedFiles.Clear();
                        file.IsSelected = true;
                        SelectedFiles.Add(file);
                    }
                    return true;
                case FileSelectionMode.Multiple:
                    file.IsSelected = true;
                    if (!SelectedFiles.Contains(file))
                    {
                        file.IsSelected = true;
                        SelectedFiles.Add(file);
                        if (SelectedFilesChanged != null)
                            SelectedFilesChanged(this, EventArgs.Empty);
                    }
                    return true;
            }
            return false;
        }

        public bool UnselectFile(FileItemData file)
        {
            file.IsSelected = false;
            return true;
        }

        public static readonly DependencyProperty DirectoryPathProperty =
            DependencyProperty.Register("DirectoryPath", typeof(String), typeof(UFileExplorer), new UIPropertyMetadata(""));


        public ObservableCollection<FileItemData> Files
        {
            get { return (ObservableCollection<FileItemData>)GetValue(FilesProperty); }
            protected set { SetValue(FilesProperty, value); }
        }

        public static readonly DependencyProperty FilesProperty =
            DependencyProperty.Register("Files", typeof(ObservableCollection<FileItemData>), typeof(UFileExplorer), new UIPropertyMetadata(new ObservableCollection<FileItemData>()));


        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            Back();
        }

        private void FreshButton_Click(object sender, RoutedEventArgs e)
        {
            Fresh();
        }

        #region Events

        public event EventHandler SelectedFilesChanged;

        #endregion
    }

    public enum FileSelectionMode
    {
        None,
        Single,
        Multiple,
    }

}
